<!-- 保存图形文件到系统后台 -->
<template>
  <div>
      <el-dialog   :modelValue="dialogVisible"  title="文件"  width="40%"
                  :close-on-click-modal="false" :close-on-press-escape="false"
                  :show-close="false" >

                  <!-- <el-radio-group v-model="picfrom" >
                    <el-radio value="1" size="large" @change="handleChange" >系统图像</el-radio>
                    <el-radio value="2" size="large" @change="handleChange" >项目图像</el-radio>
                  </el-radio-group> -->
                  <!-- {{ picfrom }} -->
                    <div style="margin-bottom: 10px;">
                      <el-button :class="{ 'btn-select': picfrom === '1' }"  @click="handleSystem" round>系统图像</el-button>
                      <el-button :class="{ 'btn-select': picfrom === '2' }"  @click="handleProject" round>项目图像</el-button>
                    </div>

                  <div  style="display: flex; flex-direction: row; width: 100%; " >
                      <el-tree  ref="dir" :data="listDir" 
                          class="clsTree"
                          :props="defaultProps" 
                          node-key="path" 
                          :current-node-key="currentDir"  
                          highlight-current  
                          :default-expanded-keys="defaultobj"
                          @node-click="changeDir"
                          >
                          <!-- <template #default="{ node, data }">
                              <span :style="{ backgroundColor:  'blue' }">{{ node.label }}</span>
                          </template> -->
                       
                      </el-tree>
                      <el-tree  ref="file" :data="listFile" 
                          class="clsTree"
                          :props="defaultProps" 
                          node-key="path"  
                          :default-expanded-keys="defaultobjfile"
                          default-expand-all>
                          <template #default="{ node, data }">
                              <span style="margin-right: 20px">{{ node.label }}</span>
                              <ComptDisplayPic :dirpath="updatePathBySrcFrom(data.path)" :picfilename="node.label" ></ComptDisplayPic>
                          </template>   
                      </el-tree>

                  </div>

                  <div  style="display: flex; flex-direction: row; width: 100%; margin-top: 20px;" >
                    <el-dropdown style="width: 100px;"   @command="handleDirFunc" >
                      <span>
                        目录操作
                        <el-icon><ArrowDownBold /></el-icon>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="adddir">增加</el-dropdown-item>
                          <el-dropdown-item command="deldir" >删除</el-dropdown-item>
                          <el-dropdown-item command="renamedir" >重命名</el-dropdown-item>
                          <el-dropdown-item command="freshdir" >刷新目录</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>

                    <el-dropdown style="width: 100px;"   @command="handleFileFunc" >
                      <span>
                        文件操作
                        <el-icon><ArrowDownBold /></el-icon>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="delfile" >删除</el-dropdown-item>
                          <el-dropdown-item command="renamefile" >重命名</el-dropdown-item>

                          <el-dropdown-item command="downloadfile" >下载文件</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                    <ComptUploadFile  :dirpath="currentDir"  :basedir="baseDir"  @res-filename="handleUpload" ></ComptUploadFile>
                    <span v-if="configNewFile" style="width: 200px;" >新文件名：</span>
                    <el-input v-if="configNewFile"  v-model="newFileName" ></el-input>

                </div>



        <template #footer>
          
          <!-- <el-button @click="handleTest">测试</el-button> -->
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="handleOk">确 定</el-button>
        </template>
      </el-dialog>

  </div>
</template>

<script>

import {ElMessage, ElMessageBox} from "element-plus"
import { mapState } from 'vuex'
import request from "@/utils/drawutils/request";
import {ArrowDownBold} from "@element-plus/icons-vue";
import { nextTick } from "vue";
import { download } from "../js/download";
import ComptUploadFile from "../compt/ComptUploadFile.vue";
import ComptDisplayPic from "../compt/ComptDisplayPic.vue";

export default {
  name: "DlgBackPicFile",
  props:{ dialogVisible: Boolean, configNewFile: Boolean },
  components:{ArrowDownBold, ComptUploadFile, ComptDisplayPic},
  emits:[ "resFile" ],

  computed: mapState([
        'projectid',
        'projectExist'
    ]),  

  async mounted() {

    let obj = {  parent: '/', subdir: '',  picpath: "",  projectid: this.projectid  }
      // console.log( obj )
      let res = await request.post("/dirfilem/makedir",  obj )
      this.handleChange(  )
      // if( res.code === "1" )
      //     this.handleChange(  )

    // setTimeout(() => {
    //     //在images中创建项目目录
    //   let obj = {  parent: '/', subdir: '',  picpath: "",  projectid: this.projectid  }
    //   // console.log( obj )
    //   request.post("/dirfilem/makedir",  obj )

    //   this.handleChange(  )

    // }, 1000);    
  },
  
  data(){
    return{
      listDir: [],
      listFile: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      currentDir: "",
      baseDir: "system",  //后中的基目录，如果是系统图像则是system 如果是项目编号则是 projectid
      nodekey: "path",
      defaultobj: ["/"],
      defaultobjfile: [""],
      newFileName:  "",
      picfrom: "1",     //图像来源的类型 可以是系统也可以是项目

    }
  },
  watch: {

  },
  methods:{
    download : download,

    async getDir(  path ){
      let param = {dir: path, picpath: "1" }
      this.addParamBySrcFrom( param )
      // console.log( "param:", param )

      request.post("/dirfilem/getdir",  param ).then(res => {
        // console.log( res )
        if( res.code === "1" ){
          this.listDir = []
          res.data.label = "后台根目录 /"
          this.listDir.push(  res.data )
          // console.log( "dir array",  this.listDir )

        }
      })
    },

    async  getFile(  path ){
      let param = {dir: path, picpath: ""}
      this.addParamBySrcFrom( param )
      
      const res = await request.post("/dirfilem/getfile", param )
      // console.log( "getFile: ",  res )
      if( res.code === "1" ){
          this.listFile = []
          this.listFile = res.data 
          
          // console.log( "listFile", this.listFile )

          // console.log( this.listFile )
      }

    },

    //保存文件
    handleOk(  ){
      const nodedir = this.$refs.dir.getCurrentNode();
      const nodefile = this.$refs.file.getCurrentNode();

      // console.log( nodedir, nodefile )
      if(  !nodedir || !nodefile ){
        ElMessage({ type: 'error',  message: "请选择要打开的文件!" })
        return
      }

      let obj = { dir:   this.updatePathBySrcFrom(nodedir.path), filename: nodefile.label }
      this.$emit( "resFile", 1, obj )
    },

    handleCancel(  ){
      this.$emit( "resFile", 0 )
    },

    handleTest(  ){
      //设置当前节点
      // this.currentDir = "333"
      // this.$refs.dir.setCurrentKey(this.currentDir);
      // console.log(  this.currentDir )

      //获取当前节点的信息
      const currentNode = this.$refs.dir.getCurrentNode();
      if (currentNode) {
        const currentNodeData = currentNode.data;
        // console.log('当前节点信息:', currentNode);
      } else {
        // console.log('没有当前节点');
      }

    },

    changeDir( data, node, component ){
      // console.log( data )
      this.currentDir = data.path
      this.getFile( data.path )
      node.expanded = true    //强制不收缩节点

      if( this.picfrom === "1" )
          this.baseDir = "system"
      else
          this.baseDir = this.projectid

    },

    freshCurrentDir(  ){
      const nodedir = this.$refs.dir.getCurrentNode();

      this.getFile( nodedir.path )
    },

    //目录操作功能
    handleDirFunc( command ){
      // console.log( command )
      if( command === "freshdir" ){
        this.getDir( "/" )
      }

      if( command === "adddir" ){
        const nodedir = this.$refs.dir.getCurrentNode();
        if( nodedir === null ){
          ElMessage({ type: 'error',  message: "请选择创建的父目录!" })
          return
        }

        ElMessageBox.prompt('请输入子目录名称', '子目录名称', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder:  "新目录",
        })
        .then(({ value }) => {
            let param = {  parent: nodedir.path, subdir: value, picpath: ""  }
            this.addParamBySrcFrom( param )

            request.post("/dirfilem/makedir",  param ).then(res => {
              // console.log( res )
              if( res.code === "1" ){
                ElMessage({ type: 'success',  message: "创建成功" })
                this.defaultobj = []
                if( nodedir.path === "/" )
                  this.defaultobj.push( '/' + value )
                else
                  this.defaultobj.push( nodedir.path + '/' + value )
                // console.log( this.defaultobj )
                this.getDir("/")
              }
              else{
                ElMessage({ type: 'error',  message: res.msg })
              }
            })
        })
        .catch(() => {
        })

      }

      if( command === "deldir" ){
        const nodedir = this.$refs.dir.getCurrentNode();
        ElMessageBox.confirm(
          '是否删除文件夹' + nodedir.label + '?',
          '警告',
          {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
          }
        )
        .then(() => {
          let param = { dir: nodedir.path , picpath: ""}
          this.addParamBySrcFrom( param )

          let index = nodedir.path.lastIndexOf('/');
          let parentdir = "/"
          if( index == 0 )
            parentdir = "/"
          else
            parentdir = nodedir.path.substring(0, index)
          // console.log( "del dir:", nodedir.path, parentdir )

          this.defaultobj = []
          this.defaultobj.push( parentdir )

          request.post("/dirfilem/deldir", param  ).then(res => {
              // console.log( res )
              if( res.code === "1" ){
                ElMessage({ type: 'success',  message: "删除成功" })
                this.getDir("/")
              }
              else{
                ElMessage({ type: 'error',  message: res.msg })
              }
            })
        })
        .catch(() => {
        })
        
      }

      if( command === "renamedir" ){
        const nodedir = this.$refs.dir.getCurrentNode();
        if( nodedir === null ){
          ElMessage({ type: 'error',  message: "请选择目录节点!" })
          return
        }

        ElMessageBox.prompt('请输入新子目录名称', '子目录名称', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue:  nodedir.label,
        })
        .then(({ value }) => {
            let param = {  oldpath: nodedir.path, newdirname: value, picpath: "" }
            this.addParamBySrcFrom( param )

            request.post("/dirfilem/renamedir",  param ).then(res => {
              // console.log( res )
              if( res.code === "1" ){
                ElMessage({ type: 'success',  message: "更名成功" })
                
                //自动选中更新目录
                const lastIndex = nodedir.path.lastIndexOf('/');
                const beforeLastSlash = nodedir.path.substring(0, lastIndex);
                this.defaultobj = []
                this.defaultobj.push( beforeLastSlash + '/' + value )
                this.getDir("/")
              }
              else{
                ElMessage({ type: 'error',  message: res.msg })
              }
            })
        })
        .catch(() => {

        })
        
      } // end if

    },

    //对文件的处理
    handleFileFunc( command ){
      const nodedir = this.$refs.dir.getCurrentNode();
      const nodefile = this.$refs.file.getCurrentNode();

      // console.log( nodedir, nodefile )
      if(  !nodedir || !nodefile ){
        ElMessage({ type: 'error',  message: "请选择要操作的文件!" })
        return
      }

      if( command === "delfile" ){
        ElMessageBox.confirm(
          '是否删除文件' + nodefile.label + '?',
          '警告',
          {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
          }
        )
        .then(() => {
          let param = { dir: nodedir.path, file: nodefile.label, picpath: "" }
          this.addParamBySrcFrom( param )

          request.post("/dirfilem/delfile", param ).then(res => {
              // console.log( res )
              if( res.code === "1" ){
                ElMessage({ type: 'success',  message: "删除成功" })
                this.getFile(nodedir.path).then(data => {
                  if( this.listFile.length > 0 ){
                    this.defaultobjfile[0] =  this.listFile[0].label 
                    // console.log( "this.defaultobjfile", this.defaultobjfile )
                    // console.log(  "new " , this.listFile[0].label )
                    this.$refs.file.setCurrentKey( this.listFile[0].label  )
                  }
                })
              }
              else{
                ElMessage({ type: 'error',  message: res.msg })
              }
            })
        })
        .catch(() => {
        })
        
      }  // end if 

      //文件更名
      if( command === "renamefile" ){
        ElMessageBox.prompt('请输入新文件名称', '子目录名称', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue:  nodefile.label,
        })
        .then(({ value }) => {
          let param = {  path: nodedir.path, oldfile : nodefile.label , newfile: value, picpath: "" }
          this.addParamBySrcFrom( param )

          request.post("/dirfilem/renamefile",  obj ).then(res => {
            // console.log( res )
            if( res.code === "1" ){
              ElMessage({ type: 'success',  message: "更名成功" })
              this.getFile( nodedir.path )
            }
            else{
              ElMessage({ type: 'error',  message: res.msg })
            }
          })
        })
        .catch(() => {

        })
        
      } // end if

      //下载指定的文件
      if( command === "downloadfile" ){
          this.download( "/drawapi/drwfiles/get?dirpath=dir:" + nodedir.path +  
          "&filename=" + nodefile.label + "&basedir=" + this.baseDir, nodefile.label )
      }

    },  // end handleFileFunc

    handleUpload(  ){
      this.freshCurrentDir(  )
    },

    addParamBySrcFrom( param ){
      if( this.picfrom === "2" ){
        param.projectid = this.projectid
      }
      return param 
    },

    updatePathBySrcFrom( path ){
      if( this.picfrom === "1" ){
        // console.log( "system: ", "/system" + path )
        return "/system" + path
      }
      else if( this.picfrom === "2" ){
        // console.log( "projectid: ", "/" + this.projectid + path )
        return "/" + this.projectid + path
      }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
    },

    //切换图形
    async handleChange(  ){
      this.listDir = [ ]
      this.listFile = [ ]

      console.log( "picfrom:", this.picfrom, this.projectExist )
      if( this.projectExist ){
          await this.getDir( "/"  )
          await this.getFile( "/" )
          this.defaultobj = []
          this.defaultobj.push( '/' )
        }
    },

    handleSystem(  ){
      this.listDir = [ ]
      this.listFile = [ ]
      this.picfrom = "1"
      this.handleChange(  )
    },

    handleProject(  ){
      this.listDir = [ ]
      this.listFile = [ ]
      this.picfrom = "2"
      this.handleChange(  )
    }    

  },  // end of methods

}

</script>

<style  lang="less" scoped >

.clsTree{
  border: 1px solid black;  
  flex: 1; 
  height: 50vh; 
  overflow-y: auto;
}

::v-deep( .el-tree .el-tree-node.is-current > .el-tree-node__content ){
          background-color: rgb(121, 235, 201); /* 选择你想要的颜色 */
}

.btn-select {
  background-color: green;
  color: white;
  border-color: green;
}

</style>